package com.itheima.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.OSSObject;
import com.itheima.common.R;
import com.itheima.util.UploadUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

@RestController
@RequestMapping("/common")
public class CommonControllers {
    @PostMapping("/upload")
    public R upload(MultipartFile file) throws IOException {
        String upload = UploadUtils.upload(file);
        return R.success(upload);


    }


    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        String endpoint="https://oss-cn-hangzhou.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5t7MrWWJT73SBtEnwFVK";
        String accessKeySecret = "BDaDaofiVLCIBODQSQYGrKqteL6DO3";
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "qianziwei12138";
        // 填写Object完整路径，例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
        String objectName = name;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 调用ossClient.getObject返回一个OSSObject实例，该实例包含文件内容及文件元信息。
            OSSObject ossObject = ossClient.getObject(bucketName, objectName);

            IOUtils.copy(ossObject.getObjectContent(),response.getOutputStream());

        } catch (OSSException oe) {

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }


    }
}
